

export default {
    namespaced:true,
    state:{
        carts:[]
    },
    mutations:{
        //添加到购物车
        ADD_CARTS(state,payload){
            let target = state.carts.find(item=>item.id===payload.id)
            if(!target){
               let obj = {
                title:payload.title,
                id:payload.id,
                price:payload.price,
                count:1
               }
               state.carts.push(obj)
            }else{
                target.count ++
            }
        },
        //让数量减少
        DEL_CART(state,payload){
            let target = state.carts.find(item=>item.id===payload.id)
            if(target){
                target.count --
            }
            state.carts = state.carts.filter(item=>item.count!=0)
        }

    },
    actions:{
        //让数量减少
        DEL_COUNT(context,payload){
            context.commit('DEL_CART',payload),
            context.commit('product/ADD_INVENTORY',payload,{root:true})
        }
        
    },
    //总价计算
    getters:{
        total(state){
            return (state.carts.reduce((total,item)=>{
               return total += item.price*item.count 
            },0)).toFixed(2)
        }
    }
}